package com.origin.netlibrary

import android.accounts.NetworkErrorException
import android.util.Log
import com.origin.netlibrary.listener.DownloadListener
import com.origin.utils.log.LogUtils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
import okhttp3.MediaType
import okhttp3.ResponseBody
import retrofit2.Call
import retrofit2.Response
import java.io.IOException
import java.lang.Exception

suspend fun Call<String>.requestNet(timeout: Long = 100*1000L):
        Response<String> {


    val self = this
    return withContext(Dispatchers.IO) {
        try {
            self.execute()
        } catch (e: Exception) {
            Log.e("网络请求异常", "Exception:  $e")
            val responseBody =
                ResponseBody.create(MediaType.get("text/plain;charset=UTF-8"), e.toString())
            Response.error(10001, responseBody)
        } finally {
            NetStack.clearByCall(self)
        }


    } ?: let {
        val responseBody =
            ResponseBody.create(MediaType.get("text/plain;charset=UTF-8"), "e".toString())
        Log.e("Expand==>扩展","xxxxxx")
        Response.error(10001, responseBody)
    }


}


suspend fun Call<ResponseBody>.requestDownload(
    viewModelScope: CoroutineScope,
    saveFilePath: String,
    downloadListener: DownloadListener
):
        Response<ResponseBody>? {
    val self = this
    return withContext(Dispatchers.IO) {
        val url = self.request().url().toString()
        LogUtils._e("DownLoadService 下载的url $url")
        NetStack.saveVmMapCall(viewModelScope, self)
        LogUtils._e("DownLoadService 下载的url  xx-1")
        self.execute()
            .apply {
                LogUtils._e("DownLoadService 下载的url  xx1")
                DownDone.writeResponseToDisk(saveFilePath, this, downloadListener, url)
            }
    }
}

suspend fun Call<ResponseBody>.requestDownload(
    saveFilePath: String,
    downloadListener: DownloadListener
):
        Response<ResponseBody>? {
    val self = this
    return withContext(Dispatchers.IO) {
        self.execute()
            .apply {
                DownDone.writeResponseToDisk(saveFilePath, this, downloadListener, "")
            }
    }
}